<script setup>
import {ref, onMounted, computed} from 'vue';
import defaultAvatar from '@/assets/avater.jpg';
import axios from 'axios'
import { ElMessage  } from 'element-plus';
import {Plus} from '@element-plus/icons-vue'
import {fa} from "vuetify/locale";

// 获取用户信息
const getUser = () => {
  axios.get('/users/findById').then((resp) => {
    console.log("获取用户信息",resp.data);
    user.value = resp.data;
    // 头像路径更新
    user.value.avatar = resp.data.avatar || defaultAvatar;
    console.log(user.value);
    userEdit.value=resp.data;
    console.log(userEdit.value);
    // // 将头像路径存储到 localStorage
    // localStorage.setItem('avatar', user.value.avatar)
  });
};

//是否显示修改弹窗
const showChangePasswordDialog = ref(false);

const resetForm = () => {
  user.value.newPassword = '';
  user.value.confirmPassword = '';
};

//是否展示修改密码弹窗
const visibleupdatePassword = ()=>{
  visibleCheck.value = true;
}
//修改密码
const updatePassword = ()=>{
  axios.post(`/users/change-password`, user.value)
      .then(()=>{
        getUser()
        showChangePasswordDialog.value=false
        ElMessage.success('修改密码成功')
      }) .catch(error => {
    //发送失败
    ElMessage.error(error.response.data)})
}
const cancelUpdate=()=>{
  showChangePasswordDialog.value = false;
  resetForm();
}
//是否显示验证弹窗
const visibleCheck=ref(false)

const cancelCheck = () => {
  visibleCheck.value = false;
  user.value.oldPassword = ''; // 清空旧密码
};
//验证密码
const checkPassword = async () => {
  console.log("验证密码传递的数据", user.value);
  axios.post(`users/check-password`, user.value)
      .then(()=>{
        visibleCheck.value = false;
        ElMessage.success('验证密码成功')
        showChangePasswordDialog.value = true;
      })
      .catch(error => {
        //发送失败
        ElMessage.error(error.response.data)})
};

// 添加一个计算属性 maskedPassword，该属性根据 user.password 的长度生成相应数量的星号。
const maskedPassword = computed(() => {
  return '*'.repeat(user.value.password.length || 6); // 默认显示6个星号
});


const user = ref({
  avatar: defaultAvatar,
  username: '',
  email: '',
  phone: '',
  password: '',
});
//头像
const imageUrl = ref('');  // 存储本地图片的 URL（用于预览）

// 上传头像成功的回调函数
const handleAvatarSuccess = (response) => {
  //response 这里直接是字符串
  // 服务器返回的头像路径
  const avatarPath = response;
  user.value.avatar = avatarPath; // 更新用户头像路径
  imageUrl.value = avatarPath;  // 更新前端显示的头像路径
  localStorage.setItem('avatar', avatarPath);
  ElMessage.success('头像上传成功！');
  console.log('头像上传成功，路径：', avatarPath);
};
// 上传之前的验证
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像图片必须是 JPG 或 PNG 格式！');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过 2MB！');
    return false;
  }
  return true;
};

//修改个人信息
// 打开修改信息弹窗
const showEditModal = () => {
  editModalVisible.value = true;
};

const userEdit=ref({});
const editFormRef =ref(null);
const editModalVisible=ref(false);
// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
};

// 保存修改的信息
const saveEdit = () => {
  editFormRef.value.validate((valid) =>{
    if (valid) {
      axios.put('/users/update', userEdit.value)
          .then(() => {
            editModalVisible.value = false
            ElMessage.success('编辑成功！')
            getUser()
          })
          .catch(errorMsg => {
            ElMessage.error(errorMsg.response.data)})
    }else {
      ElMessage.error('编辑失败')
      return false;
    }
  })
};

const cancelUserUpdate=()=>{
  editModalVisible.value = false;
  editFormRef.value.resetFields();
}

onMounted(() => {
  //从localStorage中获取头像路径
  const saveAvatar =localStorage.getItem('avatar');
  console.log("初始化头像",saveAvatar)

  if (saveAvatar){
    user.value.avatar=saveAvatar;
    imageUrl.value=saveAvatar;
  }else {
    user.value.avatar=defaultAvatar;
    imageUrl.value=defaultAvatar;
  }
  getUser()
})

</script>
<template>
<div class="account-container">
<el-card class="profile-card">
  <el-form status-icon size="small" label-width="100px">
    <div class="profile-content">
      <div class="profile-avatar">
        <!-- 头像部分 -->
        <div class="avatar-container">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="头像" />
          <el-icon v-else src="@/assets/avater.jpg" class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </div>

        <!-- 上传头像按钮，放在头像下面 -->
        <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/users/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :auto-upload="true"
        >
          <el-button slot="trigger" type="primary" size="small">更换头像</el-button>
        </el-upload>
      </div>

      <!-- 个人信息部分 -->
      <div class="profile-info">
        <div>用户名：{{ user.username }}</div>
        <div>邮箱：{{ user.email }}</div>
        <div>电话号码：{{ user.phone }}</div>
        <div>密码：{{ maskedPassword }}</div>
        <el-button type="text" @click="visibleupdatePassword">修改密码</el-button>
        <el-button type="text" @click="showEditModal">修改信息</el-button>
      </div>
    </div>
  </el-form>
</el-card>

  <!-- 修改信息弹窗 -->
  <el-dialog title="修改个人信息" width="580px" v-model="editModalVisible">
    <el-form :model="userEdit" label-width="100px" :rules="rules" ref="editFormRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userEdit.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userEdit.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userEdit.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUserUpdate">取 消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
    </span>



  </el-dialog>
    <el-dialog title="验证密码" width="580px" v-model="visibleCheck" @close="cancelCheck">
      <el-form label-width="80px" :model="user" size="small">
        <el-form-item label="密码">
          <el-input v-model="user.oldPassword" type="password" placeholder="请输入原密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="cancelCheck">取消</el-button>
          <el-button type="primary" @click="checkPassword">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改密码" width="580px" v-model="showChangePasswordDialog" @close="resetForm">
      <el-form label-width="80px" :model="user" size="small">
        <el-form-item label="新密码">
          <el-input v-model="user.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="user.confirmPassword" type="password" placeholder="请确认新密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="cancelUpdate">取消</el-button>
          <el-button type="primary" @click="updatePassword">确定</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<style scoped>
/* 居中整个卡片 */
.account-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;  /* 使卡片在整个视口中垂直居中 */
}

/* 卡片样式 */
.profile-card {
  width: 100%;
  max-width: 600px;  /* 限制卡片的最大宽度 */
  padding: 20px;
  box-sizing: border-box;
}

/* 卡片内容的容器 */
.profile-content {
  display: flex;
  flex-direction: column;
  align-items: center;  /* 居中头像和信息 */
  justify-content: center;
  text-align: center;
}

/* 头像样式 */
.profile-avatar {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 48px;
  color: #dcdfe6;
  cursor: pointer;
  display: block;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 50%;
  margin-bottom: 10px;
}

.avatar-uploader {
  margin-top: 10px;
}

/* 个人信息样式 */
.profile-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.profile-info div {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
